package com.yunc.base.oss;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.PutObjectResult;
import com.yunc.base.exception.UCException;
import com.yunc.base.properties.Pro;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云存储oss
 *
 * @author taocongcong
 * @create 2018-11-12 11:29
 */
@Service
@Slf4j
public class AliyunCloudStorageService {

    @Autowired(required = false)
    private Pro pro;

    private OSSClient client;

    @PostConstruct
    private void init(){
        client = new OSSClient(pro.getAliyunEndPoint(), pro.getAliyunAccessKeyId(),
                pro.getAliyunAccessKeySecret());
    }

    public String upload(byte[] data, String path) {
        try {
            return upload(new ByteArrayInputStream(data), path);
        } catch (Exception e) {
            log.info("上传阿里云文件失败，时间{}", DateUtil.formatDateTime(new Date()));
            throw new UCException("上传文件失败，请核对配置信息", e);
        }
    }

    public String upload(InputStream inputStream, String path) {
        try {
            PutObjectResult putObjectResult = client.putObject(pro.getAliyunBucketName(), path, inputStream);
            ResponseMessage response = putObjectResult.getResponse();
        } catch (Exception e) {
            throw new UCException("上传文件失败", e);
        }
        return pro.getAliyunDomain() + "/" + path;
    }

    public String upload(byte[] data) {
        return upload(data, getPath(pro.getAliyunPrefix()));
    }

    public String upload(InputStream inputStream) {
        return upload(inputStream, getPath(pro.getAliyunPrefix()));
    }

    private String getPath(String prefix){
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtil.format(new Date(), "yyyyMMdd") + "/" + uuid;
        if (StringUtils.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }
        return path;
    }
}
